package com.thinkcms.seo.seo.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.thinkcms.core.handler.CustomException;
import com.thinkcms.core.utils.ApiResult;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class OkHttpUtil {
    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");//mdiatype 这个需要和服务端保持一致
    private static OkHttpClient okHttpClient;
    private static JSONObject jsonObject;

    private static OkHttpClient getInstance() {
        if (okHttpClient == null) {
            HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
            synchronized (OkHttpUtil.class) {
                if (okHttpClient == null) {
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)//10秒连接超时
                            .writeTimeout(10, TimeUnit.SECONDS)//10m秒写入超时
                            .readTimeout(10, TimeUnit.SECONDS)//10秒读取超时
                            .cookieJar(new CookieJar() {
                                @Override
                                public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                                    cookieStore.put(httpUrl.host(), list);
                                }

                                @Override
                                public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                                    List<Cookie> cookies = cookieStore.get(httpUrl.host());
                                    return cookies != null ? cookies : new ArrayList<Cookie>();
                                }
                            })
                            .addInterceptor(new HttpHeaderInterceptor())//头部信息统一处理
                            //.addInterceptor(new CommonParamsInterceptor())//公共参数统一处理
                            .build();
                }
            }
        }
        return okHttpClient;
    }


    /**
     * @param url      url地址
     * @param callBack 请求回调接口
     */
    public static void getSync(String url,HttpCallBack callBack) {
        commonGetSync(getRequestForGet(url, null, null), ApiResult.class,callBack);
    }


    /**
     * @param url      url地址
     * @param callBack 请求回调接口
     */
    public static void get(String url, HttpCallBack callBack) {
        commonGet(getRequestForGet(url, null, null), ApiResult.class, callBack);
    }

    /**
     * @param url      url地址
     * @param cls      泛型返回参数
     * @param callBack 请求回调接口
     */
    public static <T extends ApiResult> void get(String url, Class<T> cls, HttpCallBack callBack) {
        commonGet(getRequestForGet(url, null, null), cls, callBack);
    }

    /**
     * @param url      url地址
     * @param params   HashMap<String, String> 参数
     * @param callBack 请求回调接口
     */
    public static void get(String url, HashMap<String, String> params, HttpCallBack callBack) {
        commonGet(getRequestForGet(url, params, null), ApiResult.class, callBack);
    }

    /**
     * @param url      url地址
     * @param params   HashMap<String, String> 参数
     * @param cls      泛型返回参数
     * @param callBack 请求回调接口
     */
    public static <T extends ApiResult> void get(String url, HashMap<String, String> params, Class<T> cls, HttpCallBack callBack) {
        commonGet(getRequestForGet(url, params, null), cls, callBack);
    }

    /**
     * @param url      url地址
     * @param params   HashMap<String, String> 参数
     * @param callBack 请求回调接口
     * @param tag      网络请求tag
     */
    public static void get(String url, HashMap<String, String> params, HttpCallBack callBack, Object tag) {
        commonGet(getRequestForGet(url, params, tag), ApiResult.class, callBack);
    }

    /**
     * @param url      url地址
     * @param params   HashMap<String, String> 参数
     * @param callBack 请求回调接口
     * @param cls      泛型返回参数
     * @param tag      网络请求tag
     */
    public static <T extends ApiResult> void get(String url, HashMap<String, String> params, Class<T> cls, HttpCallBack callBack, Object tag) {
        commonGet(getRequestForGet(url, params, tag), cls, callBack);
    }


    /**
     * @param url      url地址
     * @param callBack 请求回调接口
     */
    public static void post(String url, HttpCallBack callBack) {
        commonPost(getRequestForPost(url, null, null), ApiResult.class, callBack);
    }

    /**
     * @param url      url地址
     * @param cls      泛型返回参数
     * @param callBack 请求回调接口
     */
    public static <T extends ApiResult> void post(String url, Class<T> cls, HttpCallBack callBack) {
        commonPost(getRequestForPost(url, null, null), cls, callBack);
    }


    /**
     * @param url      url地址
     * @param params   HashMap<String, Object> 参数
     * @param callBack 请求回调接口
     */
    public static void post(String url, HashMap<String, Object> params, HttpCallBack callBack) {
        commonPost(getRequestForPost(url, params, null), ApiResult.class, callBack);
    }

    /**
     * @param url      url地址
     * @param params   HashMap<String, Object> 参数
     * @param callBack 请求回调接口
     * @param tag      网络请求tag
     */
    public static void post(String url, HashMap<String, Object> params, HttpCallBack callBack, Object tag) {
        commonPost(getRequestForPost(url, params, tag), ApiResult.class, callBack);
    }

    /**
     * @param url      url地址
     * @param params   HashMap<String, Object> 参数
     * @param cls      泛型返回参数
     * @param callBack 请求回调接口
     */
    public static <T extends ApiResult> void post(String url, HashMap<String, Object> params, Class<T> cls, final HttpCallBack callBack) {
        commonPost(getRequestForPost(url, params, null), cls, callBack);
    }


    /**
     * GET请求 公共请求部分
     */
    private static <T extends ApiResult> void commonGetSync(Request request, final Class<T> cls, final HttpCallBack callBack) {
        if (request == null) return;
        Call call = getInstance().newCall(request);
        Response response= null;
        try {
            response = call.execute();
            if(response.isSuccessful()){
                ApiResult apiResult =ApiResult.result(response.body().string());
                String url=response.request().url().toString();
                apiResult.put("requestUrl",url);
                callBack.onSuccess(call,apiResult);
            }else{
                callBack.onFailure(call,new CustomException(ApiResult.result(response.message())));
            }
        } catch (IOException e) {
            callBack.onFailure(call,e);
            e.printStackTrace();
        }

    }

    /**
     * GET请求 公共请求部分
     */
    private static <T extends ApiResult> void commonGet(Request request, final Class<T> cls, final HttpCallBack callBack) {
        if (request == null) return;
        Call call = getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                try {
                    if (callBack != null) {
                        callBack.onFailure(call, e);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            }

            @Override
            public void onResponse(Call call, Response response) {
                try {
                    if (callBack != null && response.body().string() != null) {
                        System.out.println(response.body().string());
                        callBack.onSuccess(call, ApiResult.result(response.body().string()));
                    } else {
                        log.error("caoliang", "HttpUtil----commonGet()---onResponse()--->" + response.body().string());
                    }
                } catch (Exception e) {
                    log.error("caoliang", "HttpUtil----commonGet()---onResponse()--->" + e.getMessage());
                }
            }
        });
    }

    /**
     * POST请求 公共请求部分
     */
    private static <T extends ApiResult> void commonPost(Request request, final Class<T> cls, final HttpCallBack callBack) {
        if (request == null) return;
        Call call = getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                try {
                    if (callBack != null) {
                        callBack.onFailure(call, e);
                    }
                } catch (Exception e1) {
                    log.error("caoliang", "HttpUtil----commonPost()---onFailure()--->" + e1.getMessage());
                }
            }

            @Override
            public void onResponse(Call call, Response response) {
                try {
                    if (callBack != null && response.body() != null) {
                        callBack.onSuccess(call, ApiResult.result(response.body().string()));
                    }
                } catch (Exception e) {
                    log.error("caoliang", "HttpUtil----commonPost()---onResponse()--->" + e.getMessage());
                }
            }

        });
    }

    private static Request getRequestForPost(String url, Map<String, Object> params, Object tag) {
        if (url == null || "".equals(url)) {
            log.error("caoliang", "HttpUtil----getRequestForPost()---->" + "url地址为空 无法执行网络请求!!!");
            return null;
        }
        if (params == null) {
            params = new HashMap<>();
        }
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, JSON.toJSONString(params));
        Request request;
        if (tag != null) {
            request = new Request.Builder().url(url).post(body).tag(tag).build();
        } else {
            request = new Request.Builder().url(url).post(body).build();
        }
        return request;
    }

    private static Request getRequestForGet(String url, HashMap<String, String> params, Object tag) {
        if (url == null || "".equals(url)) {
            log.error("caoliang", "HttpUtil----getRequestForGet()---->" + "url地址为空 无法执行网络请求!!!");
            return null;
        }
        Request request;
        if (tag != null) {
            request = new Request.Builder()
                    .url(paramsToString(url, params))
                    .tag(tag)
                    .build();
        } else {
            request = new Request.Builder()
                    .url(paramsToString(url, params))
                    .build();
        }
        return request;
    }

    private static String getCommonParamsForGet(StringBuilder sb) {
        return sb.toString();

    }

    /**
     * Post 添加公共参数
     */
    private static JSONObject getCommonParamsForPost() {
        jsonObject = new JSONObject();
        try {
        } catch (Exception e) {
            return jsonObject;
        }
        return jsonObject;
    }


    private static String paramsToString(String url, HashMap<String, String> params) {
        StringBuilder url_builder = new StringBuilder();
        url_builder.append(url);
        if(params!=null)
        url_builder.append("?");
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                try {
                    url_builder.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                    url_builder.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        return getCommonParamsForGet(url_builder);
    }

    /**
     * 根据tag标签取消网络请求
     */
    public static void cancelTag(Object tag) {
        if (tag == null) return;
        for (Call call : getInstance().dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : getInstance().dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }


    /**
     * 取消所有请求请求
     */
    public static void cancelAll() {
        for (Call call : getInstance().dispatcher().queuedCalls()) {
            call.cancel();
        }
        for (Call call : getInstance().dispatcher().runningCalls()) {
            call.cancel();
        }
    }

}